//引入样式
require("../../assets/css/normalize.css");
require("../../assets/css/common.css");
require("../../assets/css/reset.css");
require("../../assets/fonts/iconfont.css");
require("./sports_course_play.less");

//引入模块
const dom = require("../../utils/dom.js");
const axios = require("../../utils/axios.js");

document.addEventListener("DOMContentLoaded", function () {
	//1. 渲染数据到页面上
	const fragments = JSON.parse(localStorage.getItem("fragments"));
	let n = 0; //关键点：定义一个变量控制当前播放的节
	let video = dom.get("#video");
	let proc = dom.get(".progress-bar");
	let timer = null;
	let startTime = Date.now(); //进入页面开始计时
	let duration = 0; //持续时间

	//2. 定义一个函数，用于播放视频
	function play() {
		dom.get("#curPart").textContent = n + 1;
		dom.get("#totalPart").textContent = fragments.length;
		dom.get("#title").textContent = fragments[n].title;
		video.src = axios.defaults.baseURL + fragments[n].videoUrl;
		video.play();

		//进度条
		timer = setInterval(function () {
			proc.style.width = (100 * video.currentTime) / video.duration + "%";
		}, 50);
	}
	play();

	//3. 播放一节结束，自动接下一节
	video.addEventListener("ended", function () {
		n++;
		if (n < fragments.length) {
			play();
		} else {
			n = fragments.length - 1;
		}
	});

	//4. 上一节
	dom.get(".icon-backward").addEventListener("click", function () {
		n--;
		if (n >= 0) {
			play();
		} else {
			n = 0;
		}
	});

	//5. 下一节
	dom.get(".icon-forward").addEventListener("click", function () {
		n++;
		if (n < fragments.length) {
			play();
		} else {
			n = fragments.length - 1; //设置成最后一节
		}
	});

	//6. 隐藏弹出层
	dom.get("#mask").addEventListener("click", function () {
		this.style.display = "none";
		dom.get("#box").style.display = "none";
		video.play();
	});

	//7. 点击暂停显示弹出层
	dom.get(".icon-zanting").addEventListener("click", function () {
		dom.get("#mask").style.display = "block";
		dom.get("#box").style.display = "flex";
		video.pause();

		//计算时间
		duration += Date.now() - startTime;
	});

	//8. 继续训练
	dom.get(".icon-bofang").addEventListener("click", function () {
		dom.get("#mask").style.display = "none";
		dom.get("#box").style.display = "none";
		video.play();

		//重新计时
		startTime = Date.now();
	});

	//9. 结束训练
	dom.get("#endBox").addEventListener("click", function () {
		duration = Math.floor(duration / 1000);
		let calorie = Math.ceil(duration * 1.57);

		axios
			.post("/api/exercise/save", {
				type: 2,
				duration,
				calorie,
			})
			.then((res) => {
				if (res.data.errno === 0) {
					alert("训练结束，欢迎下次再来");
					location.href = "sports_course.html";
				}
			});
	});
});
